import { ref } from 'vue'
import {defineStore} from 'pinia'
import {loginAPI,LoginParams,LoginResult} from '@/axios/api/login/login'
import {constantRoute,asyncRouter,anyRoute} from '@/route/routes'
import router from '@/route/index'
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
//@ts-ignore
import CryptoJS from 'crypto-js'

import {setToken_local,getToken_local,setToken_session,getToken_session} from '@/utils/token'

import LocalForageInstance from '@/utils/localforage';

const db = LocalForageInstance.getInstance();

// 定义一个密钥
const SECRET_KEY = 'your-secret-key'

// 加密函数
function encrypt(data:any) {
    return CryptoJS.AES.encrypt(JSON.stringify(data), SECRET_KEY).toString()
  }

  // 解密函数
function decrypt(data:any) {
    const bytes = CryptoJS.AES.decrypt(data, SECRET_KEY)
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8))
  }

const useUserStore = defineStore('user', ()=>{
    let username=ref()
    let access_token=ref(getToken_session('access_token')||'')
    let refresh_token=ref(getToken_local('refresh_token')||'')
    let userr_all_routes=ref<any[]>(constantRoute)


   

    function filterAsyncRoutes(arouter:any,backRoutes:any){
      return  arouter.filter((item:any)=>{
            if (backRoutes.includes(item.name)) {
                if (item.children && item.children.length > 0) {
                    item.children=filterAsyncRoutes(item.children,backRoutes)
                }
                return true
            }
        })
    }

    function resetRouter(userinfo:any){
        userinfo.forEach((item:any)=>{
            router.addRoute(item)
            })
    }
    // 登录接口
    const userlogin=async (userList:LoginParams)=>{
        let res:LoginResult=await loginAPI(userList)
        if(res.code===200){
            access_token.value=res.data.access_token; 
            refresh_token.value=res.data.refresh_token; 
            username.value=res.data.username;
           
            
            setToken_session('access_token',res.data.access_token);
            setToken_local('refresh_token',res.data.refresh_token);
            db.setdb('username',res.data.username);
            db.setdb('buttons',encrypt(res.data.buttons));
            db.setdb('routes',encrypt(res.data.routes));
            // 过滤异步路由
           let filterRoutes= filterAsyncRoutes(cloneDeep(asyncRouter),res.data.routes);
           
           userr_all_routes.value=[...constantRoute,...filterRoutes,anyRoute];
           resetRouter([...filterRoutes,anyRoute]); // 重置路由
            return 'ok';
        }else{
            return Promise.reject(new Error('登录失败'));
        }
    }

    // 退出登录
    const userlogout=function (){
        access_token.value='';
        refresh_token.value='';
        sessionStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
        db.remove('username');
        db.remove('buttons');
        db.remove('routes');
        userr_all_routes.value=[];
        username.value='';
        return 'ok';
    }

    return {

        userlogin,
        access_token,
        refresh_token,
        userr_all_routes,
        resetRouter,
        filterAsyncRoutes,
        encrypt,
        decrypt,
        username,
        userlogout
    }
})

export default useUserStore
